package com.growthsee.rider.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.growthsee.common.core.controller.BaseController;
import com.growthsee.common.core.domain.AjaxResult;
import com.growthsee.common.core.page.PageDomain;
import com.growthsee.common.core.page.TableDataInfo;
import com.growthsee.common.utils.SecurityUtils;
import com.growthsee.common.utils.StringUtils;
import com.growthsee.common.utils.bean.BeanUtils;
import com.growthsee.rider.constant.ConstantConfig;
import com.growthsee.rider.domain.RiderCompany;
import com.growthsee.rider.domain.RiderInfo;
import com.growthsee.rider.domain.RiderInfoCar;
import com.growthsee.rider.domain.dto.RiderInfoDto;
import com.growthsee.rider.domain.view.RiderInfoView;
import com.growthsee.rider.domain.view.TrafficPoliceMsg;
import com.growthsee.rider.enumeration.RegisterEnum;
import com.growthsee.rider.enumeration.YesNoEnum;
import com.growthsee.rider.mapper.RiderInfoCarMapper;
import com.growthsee.rider.param.BaseParam;
import com.growthsee.rider.service.RiderCompanyService;
import com.growthsee.rider.service.RiderInfoService;
import com.growthsee.rider.utils.BasicPathUtil;
import com.growthsee.rider.utils.BeanUtilsExt;
import com.growthsee.rider.utils.OkhttpUtil;
import com.growthsee.rider.wrapper.RiderWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author csy
 * @since 2021-05-13
 */
@AllArgsConstructor
@RestController
@RequestMapping("/rider/info")
@Api("骑手信息管理")
public class RiderInfoController extends BaseController {
    private final RiderInfoService riderInfoService;
    private final RiderCompanyService riderCompanyService;
    private final RiderInfoCarMapper riderInfoCarMapper;

    @ApiOperation(value = "分页查询骑手", notes = "分页查询骑手")
    @GetMapping
    public TableDataInfo query(PageDomain page, BaseParam baseParam) {
        Long userId =  SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<RiderInfo> queryWrapper = Wrappers.lambdaQuery();
        if(!SecurityUtils.isAdmin(userId)){
            RiderCompany riderCompany =riderCompanyService.getOne(Wrappers.<RiderCompany>lambdaQuery().eq(RiderCompany::getHeadId,userId).eq(RiderCompany::getDeleted,YesNoEnum.NO.getValue()));
            if(ObjectUtils.isEmpty(riderCompany)){
                return getDataTable(null,0);
            }
            queryWrapper.eq(RiderInfo::getPlatformCompanyId,riderCompany.getId()).or().eq(RiderInfo::getAgentCompanyId,riderCompany.getId());
        }
        queryWrapper.eq(RiderInfo::getDeleted, YesNoEnum.NO.getValue()).eq(RiderInfo::getRegisterStatus,RegisterEnum.REGISTERED.getValue());
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(baseParam.getCompanyId())){
            queryWrapper.eq(RiderInfo::getPlatformCompanyId, baseParam.getCompanyId()).or().eq(RiderInfo::getAgentCompanyId, baseParam.getCompanyId());
        }
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(baseParam.getKeywords())){
            queryWrapper.like(RiderInfo::getName, baseParam.getKeywords()).or().like(RiderInfo::getMobilePhone, baseParam.getKeywords()).or().like(RiderInfo::getLicensePlateNumber, baseParam.getKeywords());
        }
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(baseParam.getMobilePhone())){
            queryWrapper.like(RiderInfo::getMobilePhone, baseParam.getMobilePhone());
        }
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(baseParam.getLicensePlateNumber())){
            queryWrapper.like(RiderInfo::getLicensePlateNumber, baseParam.getLicensePlateNumber());
        }
        Page page1 = riderInfoService.page(new Page<>(page.getPageNum(),page.getPageSize()), queryWrapper);
        Page<RiderInfoDto> riderLoanInfoDtoPage = BeanUtilsExt.copyPageData(page1, RiderInfoDto.class);
        RiderWrapper.builder().propertyHandler(riderLoanInfoDtoPage.getRecords());
        return getDataTable(riderLoanInfoDtoPage.getRecords(),riderLoanInfoDtoPage.getTotal());
    }

    @ApiOperation(value = "注册骑手", notes = "注册骑手")
    @PutMapping
    public AjaxResult update(@RequestBody RiderInfoDto riderInfo) {
        String userNamePassWorldResult= RiderWrapper.builder().checkInfo(riderInfo.getName(),riderInfo.getIdCard());
        if(StringUtils.isNotEmpty(userNamePassWorldResult))return AjaxResult.error(userNamePassWorldResult);
        String resultVerificationCode= RiderWrapper.builder().checkVerificationCode(riderInfo);
        if(StringUtils.isNotEmpty(resultVerificationCode))return AjaxResult.error(resultVerificationCode);
        riderInfo.setUpdateBy(SecurityUtils.getUsername());
        riderInfo.setUpdateTime(new Date());
        riderInfo.setRegisterStatus(RegisterEnum.REGISTERED.getValue());
        RiderWrapper.builder().pushData(riderInfo);
        riderInfoService.updateById(riderInfo);
        return AjaxResult.success();
    }

    @ApiOperation(value = "修改车牌信息", notes = "修改车牌信息")
    @PutMapping("carNo")
    public AjaxResult carNo(@RequestBody RiderInfoCar car) {
        String result = RiderWrapper.builder().checkBaseInfo(car);
        if(StringUtils.isNotEmpty(result)){
            return AjaxResult.error(result);
        }
        addPlates(car);
        //推送数据到交管局
        RiderInfoView riderInfoView = RiderWrapper.builder().rider2RiderInfoView(car);
        try {
           String reslut = OkhttpUtil.doPostHttpRequest(BasicPathUtil.getTrafficPoliceUrl()+"user", JSONObject.toJSONString(riderInfoView));
            TrafficPoliceMsg resData = JSONArray.parseObject(reslut, TrafficPoliceMsg.class);
            if(ObjectUtils.isNotEmpty(resData)){
                if(StringUtils.equals(resData.getCode(), ConstantConfig.SYSTEM_RESULTCODE_SUCCESS)){
                    riderInfoService.update(Wrappers.<RiderInfo>lambdaUpdate()
                            .set(RiderInfo::getLicensePlateNumber,car.getLicensePlateNumber())
                            .eq(RiderInfo::getId,car.getRiderId())
                    );
                }else {
                    return AjaxResult.error(resData.getMsg());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.success();
    }


    @ApiOperation(value = "修改个人信息", notes = "修改个人信息")
    @PutMapping("/modify/personInfo/{id}")
    public AjaxResult modifyPersonInfo(@PathVariable String id, @RequestBody RiderInfoDto riderInfo) {
        RiderInfo source = riderInfoService.getById(id);
        if(StringUtils.isNotEmpty(riderInfo.getMobilePhone()) && !StringUtils.equals(riderInfo.getMobilePhone(),source.getMobilePhone())){
            String resultVerificationCode= RiderWrapper.builder().checkVerificationCode(riderInfo);
            if(StringUtils.isNotEmpty(resultVerificationCode))return AjaxResult.error(resultVerificationCode);
        }
        riderInfoService.update(Wrappers.<RiderInfo>lambdaUpdate()
                .set(RiderInfo::getNational,riderInfo.getNational())
                .set(RiderInfo::getAge,riderInfo.getAge())
                .set(RiderInfo::getProvince,riderInfo.getProvince())
                .set(RiderInfo::getCity,riderInfo.getCity())
                .set(RiderInfo::getMobilePhone,riderInfo.getMobilePhone())
                .eq(RiderInfo::getId,id)
        );
        return AjaxResult.success();
    }

    @ApiOperation(value = "拉黑、解除拉黑", notes = "拉黑、解除拉黑")
    @PutMapping("/status")
    public AjaxResult modifyStatus(@RequestBody RiderInfo riderInfo) {
        riderInfoService.updateById(riderInfo);
        return AjaxResult.success();
    }

    @ApiOperation(value = "根据id查询骑手", notes = "根据id查询骑手")
    @GetMapping("{id}")
    public AjaxResult findOne(@PathVariable String id) {
        RiderInfo riderInfo = riderInfoService.getById(id);
        RiderInfoDto riderInfoDto = new RiderInfoDto();
        BeanUtils.copyBeanProp(riderInfoDto,riderInfo);
        RiderWrapper.builder().propertyHandler(Arrays.asList(riderInfoDto));
        return AjaxResult.success(riderInfoDto);
    }

    @ApiOperation(value = "修正数据", notes = "修正数据")
    @PostMapping("/amend/{id}")
    public AjaxResult amend(@PathVariable String id) {
        RiderInfo riderInfo = riderInfoService.getById(id);
        RiderWrapper.builder().pushData(riderInfo);
        return AjaxResult.success();
    }

    /**
     * 添加车牌信息
     * @param car
     * @return
     */
    private String addPlates(RiderInfoCar car){
        car.setAgencies(car.getLicensePlateNumber().substring(0,2));
        riderInfoCarMapper.insert(car);
        return "";
    }
}


